package cn.lzd.ui.widgets;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.ColorInt;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import cn.lzd.ui.R;
import com.blankj.utilcode.util.SizeUtils;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

import java.util.concurrent.TimeUnit;

/**
 * @author lizhidong
 * 选中状态时会缩放，同时下方显示下划线
 * 显示文本 {@link SelectScaleTextView#mainText}
 * 字体尺寸从 {@link SelectScaleTextView#minTextSize} 到 {@link SelectScaleTextView#maxTextSize}
 * 由 {@link SelectScaleTextView#isSelected} 控制
 */
public class SelectScaleTextView extends ConstraintLayout {
    private boolean isSelected;
    private final float minTextSize;
    private final float maxTextSize;
    private float nowTextSize;
    private @ColorInt
    final int textColor;
    private String mString;

    private TextView mainText;
    private View bottomLine;

    private Disposable animDisposable;
    // 动画时长
    private final int delayTime = 300;
    // 帧间距
    private final int frameTime = 10;

    public SelectScaleTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SelectScaleTextView);
        isSelected = typedArray.getBoolean(R.styleable.SelectScaleTextView_sstv_selected, false);
        minTextSize = typedArray.getDimension(R.styleable.SelectScaleTextView_sstv_minTextSize
                , SizeUtils.dp2px(14));
        maxTextSize = typedArray.getDimension(R.styleable.SelectScaleTextView_sstv_maxTextSize
                , SizeUtils.dp2px(18));
        mString = typedArray.getString(R.styleable.SelectScaleTextView_sstv_text);
        mString = mString == null ? "" : mString;
        textColor = typedArray.getColor(R.styleable.SelectScaleTextView_sstv_textColor, ContextCompat.getColor(getContext(), R.color.base_ui_white));
        typedArray.recycle();
        initView();
    }

    private void initView() {
        bottomLine = new View(getContext());
        bottomLine.setId(View.generateViewId());
        bottomLine.setVisibility(isSelected ? VISIBLE : INVISIBLE);
        bottomLine.setBackground(ContextCompat.getDrawable(getContext(), R.drawable.uibase_white_c_max));
        LayoutParams bottomParams = new LayoutParams(
                SizeUtils.dp2px(25),
                SizeUtils.dp2px(3));
        bottomParams.startToStart = LayoutParams.PARENT_ID;
        bottomParams.endToEnd = LayoutParams.PARENT_ID;
        bottomParams.bottomToBottom = LayoutParams.PARENT_ID;
        bottomParams.bottomMargin = SizeUtils.dp2px(4.5f);
        addView(bottomLine, bottomParams);

        mainText = new TextView(getContext());
        mainText.setText(mString);
        mainText.setTextColor(textColor);
        nowTextSize = isSelected ? maxTextSize : minTextSize;
        mainText.setTextSize(TypedValue.COMPLEX_UNIT_PX, nowTextSize);
        mainText.setGravity(Gravity.CENTER);
        mainText.setIncludeFontPadding(false);
        LayoutParams mainParams = new LayoutParams(LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mainParams.topToTop = LayoutParams.PARENT_ID;
        mainParams.bottomToTop = bottomLine.getId();
        addView(mainText, mainParams);
    }

    public void updateSelect(boolean selected) {
        // 更新选中状态，并开始动画
        if (isSelected == selected) {
            return;
        }
        if (animDisposable != null) {
            animDisposable.dispose();
        }
        isSelected = selected;
        animDisposable = Observable.interval(frameTime, TimeUnit.MILLISECONDS)
                .map(aLong -> {
                    // 计算字号
                    float targetTextSize = isSelected ? maxTextSize : minTextSize;
                    if (nowTextSize == targetTextSize) {
                        return false;
                    }
                    float unit = (maxTextSize - minTextSize) / (((float) delayTime) / frameTime);
                    float offset = Math.abs(targetTextSize - nowTextSize);
                    float realOffsetSize = Math.min(unit, offset);
                    nowTextSize += realOffsetSize * (isSelected ? 1 : -1);
                    return true;
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(rst -> {
                    // 显示字号
                    mainText.setTextSize(TypedValue.COMPLEX_UNIT_PX, nowTextSize);
                    // 根据字号显示下方标记
                    float alpha = (nowTextSize - minTextSize) / (maxTextSize - minTextSize);
                    bottomLine.setAlpha(alpha);
                    bottomLine.setVisibility(alpha == 0 ? INVISIBLE : VISIBLE);

                    if (!rst) {
                        // 已完成，结束
                        if (animDisposable != null) {
                            animDisposable.dispose();
                        }
                    }
                });
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        // 移出视图，结束
        if (animDisposable != null) {
            animDisposable.dispose();
        }
    }


    @Override
    public boolean isSelected() {
        return isSelected;
    }
}
